//
//  PlanPeopleTotalVC.m
//  WanCaiC8
//
//  Created by tangang on 2018/5/2.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "PlanPeopleTotalVC.h"
#import "PlanPeopleHeadView.h"
#import "PlanVM.h"
#import "MyVM.h"
#import "UserInfoModel.h"
#import "LabCell.h"
#import "GradesModel.h"
#import "MyGradesCell.h"
#import "MyGradesContentCell.h"
#import "CommentVM.h"
#import "CommentsCell.h"
#import "OtherInfoVC.h"
#import "CommentDetailVC.h"
#import "CommentListVC.h"
#import "CommentsTextView.h"
#import "ExceptionalVC.h"
@interface PlanPeopleTotalVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) UserInfoModel *userModel;
@property (nonatomic ,strong) PlanPeopleHeadView  *headView;
@property (nonatomic ,strong) BetModel         *betModel;
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (nonatomic ,strong) NSMutableArray *goodComments;
@property (nonatomic ,strong) UIView        *bottomView;
@property (nonatomic ,strong) CommentsTextView *cTextView;
@property (nonatomic ,strong) NSMutableArray *commentsImages;
@end

@implementation PlanPeopleTotalVC{
    RITLPhotoNavigationViewModel * viewModel;
    NSInteger   selectRow;
    NSString    *selectModelId;
    
    NSString       *sendStr;
    QXLable         *labCount;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    viewModel = [RITLPhotoNavigationViewModel new];
    [self loadData];
    [self getComment];
    [self.tableView reloadData];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)backClick{
    [super backClick];
    [self.headView cancleTimer];
}

- (void)loadData{
    WS(weakSelf);
    [[PlanVM manage] getUserLastPlayWithUid:self.model.UserId withPlayName:@"全部" WithLtype:[self.lotteryModel.lType integerValue] WithSuccess:^(id returnValue) {
        weakSelf.betModel=[BetModel mj_objectWithKeyValues:[returnValue objectForKey:@"ExtraData"]];
//        if (weakSelf.betModel) {
//            [weakSelf.headView updateStatus:NO];
//        }else{
//            [weakSelf.headView updateStatus:YES];
//        }
        weakSelf.dataArr=[GradesModel mj_objectArrayWithKeyValuesArray:[returnValue objectForKey:@"PageData"]];
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 获取评论
- (void)getComment{
    WS(weakSelf);
    [[PlanVM manage] getWonderfulCommentId:self.lotteryModel.lType andType:1 andCount:3 andUserId:self.model.UserId Success:^(id returnValue) {
        weakSelf.goodComments=returnValue;
        [weakSelf.tableView reloadData];
        [weakSelf getCommentCount];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 获取评论条数
- (void)getCommentCount{
    [[PlanVM manage] getCommentCountWithId:self.lotteryModel.lType andType:1 andUserId:self.model.UserId Success:^(id returnValue) {
        labCount.text=[NSString stringWithFormat:@"%@",returnValue];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 查看更多回复
- (void)lookMoreReplay:(CommentModel *)model{
    CommentDetailVC *vc=[[CommentDetailVC alloc] init];
    vc.type=CommentListTypePlan;
    vc.model=model;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -- 查看全部评论
- (void)onclickCommentsList{
    CommentListVC *vc=[[CommentListVC alloc]init];
    vc.type=CommentListTypePlan;
    vc.userId=self.model.UserId;
    vc.lType=self.lotteryModel.lType;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark -- 对评论进行回复
- (void)replayComment:(CommentModel *)model{
    selectModelId=[model.Id copy];
    [self.cTextView.textView becomeFirstResponder];
}

#pragma mark -- 对评论进行点赞
- (void)likeComment:(CommentModel *)model{
    self.tableView.userInteractionEnabled=NO;
    WS(weakSelf);
    [[CommentVM manage] clickLikeWithId:model.Id andType:2 andOperationType:model.IsLike?2:1 Success:^(id returnValue) {
        [weakSelf refreshPraise:model];
    } andFail:^(NSString *errorMessage, NSError *error) {
        weakSelf.tableView.userInteractionEnabled=YES;
    }];
}

- (void)refreshPraise:(CommentModel *)model{
    BOOL isLike=!model.IsLike;
    for (CommentModel *cModel in _goodComments) {
        if ([cModel.Id isEqualToString:model.Id]) {
            cModel.IsLike=isLike;
            if (cModel.IsLike) {
                cModel.StarCount+=1;
            }else{
                cModel.StarCount-=1;
            }
        }
    }
    self.tableView.userInteractionEnabled=YES;
    [self.tableView reloadData];
}

- (void)onclickText{
    selectModelId=nil;
    [self.cTextView.textView becomeFirstResponder];
}


#pragma mark -- 发布评论
- (void)publishComment{
    WS(weakSelf);
    [SVProgressHUD show];
    [self postImageWithDoneArr:[NSMutableArray new] done:^(NSMutableArray *arr) {
        
        if (selectModelId) {
            [[PlanVM manage] publishWithId:selectModelId andType:1 andContent:[[SocketRocketUtility instance] sendMessageConversion:self.cTextView.textView.text] andCommentType:2 andUserId:self.model.UserId andPic:arr Success:^(id returnValue) {
                [self.commentsImages removeAllObjects];
                [weakSelf addRepaly];
                sendStr=nil;
                selectModelId=nil;
                [weakSelf.cTextView removeSelf];
                [SVProgressHUD dismiss];
            } andFail:^(NSString *errorMessage, NSError *error) {
                
            }];
            
        }else{
            [[PlanVM manage] publishWithId:self.lotteryModel.lType andType:1 andContent:[[SocketRocketUtility instance] sendMessageConversion:self.cTextView.textView.text] andCommentType:1 andUserId:self.model.UserId andPic:arr Success:^(id returnValue) {
                [self.commentsImages removeAllObjects];
                sendStr=nil;
                if (returnValue) {
                    if (weakSelf.goodComments.count<3) {
                        [weakSelf.goodComments addObject:returnValue];
                        [weakSelf.tableView reloadData];
                    }
                }
                selectModelId=nil;
                [weakSelf.cTextView removeSelf];
                [SVProgressHUD dismiss];
            } andFail:^(NSString *errorMessage, NSError *error) {
                
            }];
        }
        
        
    }];
    
}

- (void)addRepaly{
    for (CommentModel *cModel in _goodComments) {
        if ([cModel.Id isEqualToString:selectModelId]) {
            cModel.ReplayCount+=1;
        }
    }
    [self.tableView reloadData];
}

- (void)postImageWithDoneArr:(NSMutableArray *)doneArr done:(void(^)(NSMutableArray *arr))doneBlock{
    if (doneArr.count==self.commentsImages.count) {
        doneBlock(doneArr);
        return;
    }
    WS(weakSelf);
    [[BaseVM manage] postImageWithImage:self.commentsImages[doneArr.count] andType:3 andSuccess:^(id returnValue) {
        [doneArr addObject:[returnValue objectForKey:@"ResouceId"]];
        [weakSelf postImageWithDoneArr:doneArr done:doneBlock];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 选择照片
- (void)selectPic{
    
    if (self.commentsImages.count>2) {
        [SVProgressHUD showErrorWithStatus:@"最多只能上传3张图片"];
        return;
    }
    
    sendStr=self.cTextView.textView.text;
    [self.cTextView removeSelf];
    UIAlertController *alertCtrl=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancleAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];;
    UIAlertAction *albumAction=[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        WS(weakSelf);
        viewModel.RITLBridgeGetImageBlock = ^(NSArray  * images){
            for (NSDictionary *dict in images) {
                [weakSelf.commentsImages addObject:[dict objectForKey:@"image"]];
            }
            [weakSelf.cTextView.textView becomeFirstResponder];
        };
        self.hidesBottomBarWhenPushed = NO;
        viewModel.maxNumberOfSelectedPhoto=3-self.commentsImages.count;
        RITLPhotoNavigationViewController * viewController = [RITLPhotoNavigationViewController photosViewModelInstance:viewModel];
        [self presentViewController:viewController animated:true completion:^{}];
    }];
    UIAlertAction *cameraAction=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController * ipc = [[UIImagePickerController alloc] init];
        ipc.delegate = self;
        ipc.sourceType = sourceType;
        [self presentViewController:ipc animated:YES completion:nil];
    }];
    [alertCtrl addAction:cancleAction];
    [alertCtrl addAction:albumAction];
    [alertCtrl addAction:cameraAction];
    [self presentViewController:alertCtrl animated:YES completion:nil];
}

#pragma mark -- 打赏
- (void)exceptional{
    ExceptionalVC *vc=[[ExceptionalVC alloc]init];
    vc.model=self.model;
    vc.lotteryModel=self.lotteryModel;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - tableView输入框遮挡
- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(keyboardTop+(SCREEN_WIDTH-60)/6+10+HEIGHT_CHATBOXVIEW-(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6+5:0)));
    }];
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary* userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@(SCREEN_HEIGHT+(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6:0)));
    }];
    [UIView commitAnimations];
    
}

#pragma mark -- UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count+1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section<self.dataArr.count) {
        GradesModel *model=self.dataArr[section];
        return 1+model.BettingRecord.count;
    }
    return self.goodComments.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    return view;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section<self.dataArr.count) {
        if (indexPath.row==0) {
            MyGradesCell *cell=[tableView dequeueReusableCellWithIdentifier:@"MyGradesCell" forIndexPath:indexPath];
            GradesModel *model=self.dataArr[indexPath.section];
            cell.type=[self.lotteryModel.lType integerValue];
            cell.model=model;
            return cell;
        }else{
            MyGradesContentCell *cell=[tableView dequeueReusableCellWithIdentifier:@"MyGradesContentCell" forIndexPath:indexPath];
            GradesModel *model=self.dataArr[indexPath.section];
            cell.arr=model.LotteryNum.NumArr;
            cell.model=model.BettingRecord[indexPath.row-1];
            if (indexPath.row%2==1) {
                cell.contentView.backgroundColor=DEFAULTBGCOLOR;
            }else{
                cell.contentView.backgroundColor=[UIColor whiteColor];
            }
            return cell;
        }
    }
    CommentModel *model=self.goodComments[indexPath.row];
    WS(weakSelf);
    if (model.ReplayCount>0) {
        CommentsCell *cell=[tableView dequeueReusableCellWithIdentifier:@"CommentsCell" forIndexPath:indexPath];
        [cell setModel:model];
        cell.lookComment = ^(CommentModel *model) {
            [weakSelf lookMoreReplay:model];
        };
        cell.likeComment = ^(CommentModel *model) {
            [weakSelf likeComment:model];
        };
        cell.replayComment = ^(CommentModel *model) {
            [weakSelf replayComment:model];
        };
        cell.lookUser = ^(CommentModel *model) {
//            OtherInfoVC *vc=[[OtherInfoVC alloc]init];
//            vc.userId=model.ParentComment.UserId;
//            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }
    CommentsCell *cell=[tableView dequeueReusableCellWithIdentifier:@"CommentsCell1" forIndexPath:indexPath];
    [cell setModel:model];
    cell.lookComment = ^(CommentModel *model) {
        [weakSelf lookMoreReplay:model];
    };
    cell.likeComment = ^(CommentModel *model) {
        [weakSelf likeComment:model];
    };
    cell.replayComment = ^(CommentModel *model) {
        [weakSelf replayComment:model];
    };
    cell.lookUser = ^(CommentModel *model) {
//        OtherInfoVC *vc=[[OtherInfoVC alloc]init];
//        vc.userId=model.ParentComment.UserId;
//        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    return cell;
    
}

#pragma mark -- UINavigationControllerDelegate, UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (!self.commentsImages) {
        self.commentsImages=[[NSMutableArray alloc]init];
    }
    [self.commentsImages addObject:image];
    [self dismissViewControllerAnimated:YES completion:^{
        [self.cTextView.textView becomeFirstResponder];
    }];
    
    
}

#pragma mark -- 懒加载
- (NSMutableArray *)commentsImages{
    if (!_commentsImages) {
        _commentsImages=[[NSMutableArray alloc]init];
    }
    return _commentsImages;
}


- (UITableView *)tableView{
    if (!_tableView) {
        WS(weakSelf);
        _tableView=[[UITableView alloc]init];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        [_tableView registerClass:[MyGradesCell class] forCellReuseIdentifier:@"MyGradesCell"];
        [_tableView registerClass:[MyGradesContentCell class] forCellReuseIdentifier:@"MyGradesContentCell"];
        _tableView.backgroundColor=DEFAULTBGCOLOR;
        [_tableView registerClass:[CommentsCell class] forCellReuseIdentifier:@"CommentsCell"];
        [_tableView registerClass:[CommentsCell class] forCellReuseIdentifier:@"CommentsCell1"];
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight=UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight=100;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.top.equalTo(self.headView.mas_bottom);
            make.bottom.equalTo(self.bottomView.mas_top);
        }];
    }
    return _tableView;
}

- (PlanPeopleHeadView *)headView{
    if (!_headView) {
        WS(weakSelf);
        _headView=[[PlanPeopleHeadView alloc]init];
        _headView.userId=self.model.UserId;
        _headView.lType=self.lotteryModel.lType;
        _headView.clickExceptional = ^{
            [weakSelf exceptional];
        };
//        [_headView total];
        [self.view addSubview:_headView];
        [_headView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            make.height.mas_equalTo(@(real_size(110)));
        }];
    }
    return _headView;
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView=[[UIView alloc]init];
        _bottomView.backgroundColor=[UIColor whiteColor];
        UIView *line=[[UIView alloc]init];
        line.backgroundColor=DEFAULTBGCOLOR;
        [_bottomView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(_bottomView);
            make.height.mas_equalTo(@.7);
        }];
        
        
        UIButton  *btnReply=[[UIButton alloc]init];
        [btnReply setImage:[UIImage imageNamed:@"comments_count"] forState:UIControlStateNormal];
        [btnReply addTarget:self action:@selector(onclickCommentsList) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:btnReply];
        [btnReply mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.bottom.equalTo(_bottomView);
            make.width.mas_equalTo(@47);
        }];
        
        labCount=[[QXLable alloc]initWithFount:10];
        labCount.textAlignment=NSTextAlignmentCenter;
        labCount.textColor=NAVCOLOR;
        //        labCount.text=self.contentModel.CommentCount;
        [_bottomView addSubview:labCount];
        [labCount mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(btnReply).with.offset(8);
            make.centerY.equalTo(btnReply).with.offset(-8);
        }];
        
        UIButton *btnText=[[UIButton alloc]init];
        [btnText addTarget:self action:@selector(onclickText) forControlEvents:UIControlEventTouchUpInside];
        btnText.backgroundColor=DEFAULTBGCOLOR;
        btnText.layer.masksToBounds=YES;
        btnText.layer.cornerRadius=4.0;
        [_bottomView addSubview:btnText];
        [btnText mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(_bottomView).with.insets(UIEdgeInsetsMake(5, 10, 5, 47));
        }];
        
        
        [self.view addSubview:_bottomView];
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.height.mas_equalTo(@50);
        }];
    }
    return _bottomView;
}

- (CommentsTextView *)cTextView{
    if (!_cTextView) {
        WS(weakSelf);
        _cTextView=[[CommentsTextView alloc]init];
        _cTextView.textView.text=sendStr;
        [_cTextView setImageArr:self.commentsImages];
        _cTextView.clickEmj = ^(BOOL isFace) {
            if (isFace) {
                [weakSelf.cTextView.textView resignFirstResponder];
                [weakSelf.cTextView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(@(SCREEN_HEIGHT+(self.cTextView.imageArr.count>0?(SCREEN_WIDTH-60)/6:0)));
                }];
            }else{
                [weakSelf.cTextView.textView becomeFirstResponder];
            }
        };
        _cTextView.showPic = ^ {
            [weakSelf selectPic];
        };
        
        _cTextView.sendBlock = ^{
            [weakSelf publishComment];
            
        };
        _cTextView.removeBlock = ^{
            [weakSelf.cTextView removeFromSuperview];
            weakSelf.cTextView=nil;
        };
        [self.view addSubview:_cTextView];
        [_cTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            make.height.mas_equalTo(@0);
        }];
    }
    return _cTextView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
